import 'package:flutter/material.dart';
import '../animations/animation_config.dart';
import 'loading_widget.dart';
import 'skeleton_widget.dart';

/// 列表状态枚举
enum ListState {
  loading,
  success,
  empty,
  error,
  loadingMore,
  noMore,
}

/// 列表状态组件
/// 提供统一的列表状态管理和反馈
class ListStateWidget extends StatefulWidget {
  const ListStateWidget({
    super.key,
    required this.state,
    required this.child,
    this.onRefresh,
    this.onLoadMore,
    this.emptyWidget,
    this.errorWidget,
    this.loadingWidget,
    this.loadingMoreWidget,
    this.noMoreWidget,
    this.enablePullRefresh = true,
    this.enableLoadMore = true,
    this.skeletonItemCount = 5,
    this.customSkeletonItem,
    this.padding,
    this.physics,
  });

  /// 列表状态
  final ListState state;
  
  /// 列表内容
  final Widget child;
  
  /// 下拉刷新回调
  final Future<void> Function()? onRefresh;
  
  /// 加载更多回调
  final Future<void> Function()? onLoadMore;
  
  /// 自定义空状态组件
  final Widget? emptyWidget;
  
  /// 自定义错误状态组件
  final Widget? errorWidget;
  
  /// 自定义加载状态组件
  final Widget? loadingWidget;
  
  /// 自定义加载更多组件
  final Widget? loadingMoreWidget;
  
  /// 自定义没有更多组件
  final Widget? noMoreWidget;
  
  /// 是否启用下拉刷新
  final bool enablePullRefresh;
  
  /// 是否启用加载更多
  final bool enableLoadMore;
  
  /// 骨架屏数量
  final int skeletonItemCount;
  
  /// 自定义骨架屏项
  final Widget? customSkeletonItem;
  
  /// 内边距
  final EdgeInsetsGeometry? padding;
  
  /// 滚动物理效果
  final ScrollPhysics? physics;

  @override
  State<ListStateWidget> createState() => _ListStateWidgetState();
}

class _ListStateWidgetState extends State<ListStateWidget>
    with TickerProviderStateMixin {
  late AnimationController _fadeController;
  late Animation<double> _fadeAnimation;
  
  final ScrollController _scrollController = ScrollController();
  bool _isLoadingMore = false;

  @override
  void initState() {
    super.initState();
    _fadeController = AnimationConfig.createController(
      vsync: this,
      duration: AnimationConfig.fadeIn,
    );
    _fadeAnimation = AnimationConfig.createFadeAnimation(_fadeController);
    
    _scrollController.addListener(_handleScroll);
    _fadeController.forward();
  }

  @override
  void didUpdateWidget(ListStateWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.state != oldWidget.state) {
      _fadeController.reset();
      _fadeController.forward();
      
      if (widget.state != ListState.loadingMore) {
        _isLoadingMore = false;
      }
    }
  }

  void _handleScroll() {
    if (!widget.enableLoadMore || 
        widget.onLoadMore == null ||
        _isLoadingMore ||
        widget.state == ListState.loading ||
        widget.state == ListState.noMore) {
      return;
    }

    final maxScrollExtent = _scrollController.position.maxScrollExtent;
    final currentScrollOffset = _scrollController.offset;
    const threshold = 200; // 提前200px触发加载更多

    if (maxScrollExtent - currentScrollOffset <= threshold) {
      _loadMore();
    }
  }

  void _loadMore() async {
    if (_isLoadingMore) return;
    
    setState(() {
      _isLoadingMore = true;
    });
    
    try {
      await widget.onLoadMore!();
    } finally {
      if (mounted) {
        setState(() {
          _isLoadingMore = false;
        });
      }
    }
  }

  @override
  void dispose() {
    _fadeController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget content = _buildContent();
    
    if (widget.enablePullRefresh && widget.onRefresh != null) {
      content = RefreshIndicator(
        onRefresh: widget.onRefresh!,
        child: content,
      );
    }
    
    return FadeTransition(
      opacity: _fadeAnimation,
      child: content,
    );
  }

  Widget _buildContent() {
    switch (widget.state) {
      case ListState.loading:
        return widget.loadingWidget ?? _buildLoadingState();
      
      case ListState.empty:
        return widget.emptyWidget ?? _buildEmptyState();
      
      case ListState.error:
        return widget.errorWidget ?? _buildErrorState();
      
      case ListState.success:
      case ListState.loadingMore:
      case ListState.noMore:
        return _buildSuccessState();
    }
  }

  Widget _buildLoadingState() {
    if (widget.customSkeletonItem != null) {
      return ListView.builder(
        controller: _scrollController,
        physics: widget.physics,
        padding: widget.padding,
        itemCount: widget.skeletonItemCount,
        itemBuilder: (context, index) => widget.customSkeletonItem!,
      );
    }
    
    return ListView.builder(
      controller: _scrollController,
      physics: widget.physics,
      padding: widget.padding,
      itemCount: widget.skeletonItemCount,
      itemBuilder: (context, index) => SkeletonLayouts.listItem(),
    );
  }

  Widget _buildEmptyState() {
    return SingleChildScrollView(
      controller: _scrollController,
      physics: widget.physics ?? const AlwaysScrollableScrollPhysics(),
      padding: widget.padding,
      child: SizedBox(
        height: MediaQuery.of(context).size.height * 0.6,
        child: const EmptyStateWidget(),
      ),
    );
  }

  Widget _buildErrorState() {
    return SingleChildScrollView(
      controller: _scrollController,
      physics: widget.physics ?? const AlwaysScrollableScrollPhysics(),
      padding: widget.padding,
      child: SizedBox(
        height: MediaQuery.of(context).size.height * 0.6,
        child: ErrorStateWidget(
          onRetry: widget.onRefresh,
        ),
      ),
    );
  }

  Widget _buildSuccessState() {
    return NotificationListener<ScrollNotification>(
      onNotification: (scrollNotification) {
        if (scrollNotification is ScrollEndNotification) {
          _handleScroll();
        }
        return false;
      },
      child: CustomScrollView(
        controller: _scrollController,
        physics: widget.physics,
        slivers: [
          SliverPadding(
            padding: widget.padding ?? EdgeInsets.zero,
            sliver: SliverToBoxAdapter(child: widget.child),
          ),
          if (widget.state == ListState.loadingMore)
            SliverToBoxAdapter(
              child: widget.loadingMoreWidget ?? _buildLoadingMoreIndicator(),
            ),
          if (widget.state == ListState.noMore)
            SliverToBoxAdapter(
              child: widget.noMoreWidget ?? _buildNoMoreIndicator(),
            ),
        ],
      ),
    );
  }

  Widget _buildLoadingMoreIndicator() {
    return Container(
      padding: const EdgeInsets.all(16),
      alignment: Alignment.center,
      child: const InlineLoading(
        size: 20,
        message: '加载更多...',
      ),
    );
  }

  Widget _buildNoMoreIndicator() {
    return Container(
      padding: const EdgeInsets.all(16),
      alignment: Alignment.center,
      child: Text(
        '没有更多内容了',
        style: Theme.of(context).textTheme.bodySmall?.copyWith(
          color: Theme.of(context).colorScheme.onSurfaceVariant,
        ),
      ),
    );
  }
}

/// 空状态组件
class EmptyStateWidget extends StatelessWidget {
  const EmptyStateWidget({
    super.key,
    this.icon = Icons.inbox_outlined,
    this.title = '暂无数据',
    this.subtitle = '当前列表没有任何内容',
    this.action,
    this.iconSize = 64,
  });

  final IconData icon;
  final String title;
  final String subtitle;
  final Widget? action;
  final double iconSize;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            icon,
            size: iconSize,
            color: theme.colorScheme.onSurfaceVariant.withOpacity(0.6),
          ),
          const SizedBox(height: 16),
          Text(
            title,
            style: theme.textTheme.titleMedium?.copyWith(
              color: theme.colorScheme.onSurfaceVariant,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            subtitle,
            style: theme.textTheme.bodySmall?.copyWith(
              color: theme.colorScheme.onSurfaceVariant.withOpacity(0.7),
            ),
            textAlign: TextAlign.center,
          ),
          if (action != null) ...[
            const SizedBox(height: 24),
            action!,
          ],
        ],
      ),
    );
  }
}

/// 错误状态组件
class ErrorStateWidget extends StatelessWidget {
  const ErrorStateWidget({
    super.key,
    this.icon = Icons.error_outline,
    this.title = '加载失败',
    this.subtitle = '请检查网络连接或重试',
    this.onRetry,
    this.iconSize = 64,
  });

  final IconData icon;
  final String title;
  final String subtitle;
  final VoidCallback? onRetry;
  final double iconSize;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            icon,
            size: iconSize,
            color: theme.colorScheme.error.withOpacity(0.7),
          ),
          const SizedBox(height: 16),
          Text(
            title,
            style: theme.textTheme.titleMedium?.copyWith(
              color: theme.colorScheme.onSurfaceVariant,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            subtitle,
            style: theme.textTheme.bodySmall?.copyWith(
              color: theme.colorScheme.onSurfaceVariant.withOpacity(0.7),
            ),
            textAlign: TextAlign.center,
          ),
          if (onRetry != null) ...[
            const SizedBox(height: 24),
            OutlinedButton.icon(
              onPressed: onRetry,
              icon: const Icon(Icons.refresh),
              label: const Text('重试'),
            ),
          ],
        ],
      ),
    );
  }
}

/// 分页列表组件
/// 简化分页列表的使用
class PaginatedListView<T> extends StatelessWidget {
  const PaginatedListView({
    super.key,
    required this.state,
    required this.items,
    required this.itemBuilder,
    this.onRefresh,
    this.onLoadMore,
    this.emptyWidget,
    this.errorWidget,
    this.padding,
    this.physics,
    this.separatorBuilder,
  });

  final ListState state;
  final List<T> items;
  final Widget Function(BuildContext context, T item, int index) itemBuilder;
  final Future<void> Function()? onRefresh;
  final Future<void> Function()? onLoadMore;
  final Widget? emptyWidget;
  final Widget? errorWidget;
  final EdgeInsetsGeometry? padding;
  final ScrollPhysics? physics;
  final Widget Function(BuildContext context, int index)? separatorBuilder;

  @override
  Widget build(BuildContext context) {
    return ListStateWidget(
      state: state,
      onRefresh: onRefresh,
      onLoadMore: onLoadMore,
      emptyWidget: emptyWidget,
      errorWidget: errorWidget,
      padding: padding,
      physics: physics,
      child: separatorBuilder != null
          ? ListView.separated(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: items.length,
              itemBuilder: (context, index) => itemBuilder(context, items[index], index),
              separatorBuilder: separatorBuilder!,
            )
          : ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: items.length,
              itemBuilder: (context, index) => itemBuilder(context, items[index], index),
            ),
    );
  }
}